//全局锁现象数据不一致问题
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<unistd.h>
#include<pthread.h>
int ticket = 10000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//初始化定义锁
void* route(void* arg)
{
    char* id = (char*) arg;
    while(true)
    {
        pthread_mutex_lock(&lock);//加锁
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n",id,ticket);
            ticket--;
            pthread_mutex_unlock(&lock);//解锁
        }
        else
        {
            pthread_mutex_unlock(&lock);//解锁
            break;
        }
    }
    return nullptr;
}
int main()
{
    pthread_t t1,t2,t3,t4;
    //创建四个线程
    pthread_create(&t1,nullptr,route,(void*)"thread 1");
    pthread_create(&t2,nullptr,route,(void*)"thread 2");
    pthread_create(&t3,nullptr,route,(void*)"thread 3");
    pthread_create(&t4,nullptr,route,(void*)"thread 4");
    //回收四个线程
    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);
    return 0;
}